/*
 * @Description:
 * @Version: 3.0
 * @Autor: biao.hu
 * @Date: 2021-10-18 19:36:00
 * @LastEditors: biao.hu
 * @LastEditTime: 2021-10-18 19:50:06
 */
package waitgroup

import (
	"fmt"
	"sync"
)

// add的数值代表信号量数量，放在goroutine外
// done后会执行减1，放在goroutine内的defer里面

func Wg() {
	var wg sync.WaitGroup
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go func(i int) {
			fmt.Println(i)
			defer wg.Done()
		}(i)
	}
	wg.Wait()
	fmt.Println("finished")
}

// 不可复制
func ErrWg1() {
	var wg sync.WaitGroup
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go func(i int, wg sync.WaitGroup) {
			fmt.Println(i)
			defer wg.Done()
		}(i, wg)
	}
	wg.Wait()
	fmt.Println("finished")
}

// waitgroup 的add要在goroutine前执行
func ErrWg2() {
	var wg sync.WaitGroup
	for i := 0; i < 10; i++ {
		go func(i int) {
			wg.Add(1)
			fmt.Println(i)
			defer wg.Done()
		}(i)
	}
	wg.Wait()
	fmt.Println("finished")
}
